package com.example.goodtrash.db;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.goodtrash.model.History;
import com.example.goodtrash.model.News;
import com.example.goodtrash.model.Trash;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class GoodTrashDB {
    public static  final String DB_NAME = "good_trash";
    public  static final int VERSION = 1;
    public  static GoodTrashDB goodTrashDB;
    public SQLiteDatabase db;
    private GoodTrashDB(Context context){
        GoodTrashHelper goodTrashDB=new GoodTrashHelper(context,DB_NAME,null,VERSION);
        db=goodTrashDB.getWritableDatabase();
    }

    public synchronized static GoodTrashDB getInstance(Context context){
        if (goodTrashDB==null){
            goodTrashDB=new GoodTrashDB(context);
        }
        return goodTrashDB;
    }

    public void saveHistory(Trash trash){
        if (trash!=null){
            ContentValues values=new ContentValues();
            values.put("name",trash.getTrashName());
            values.put("type",trash.getTrashType());
            values.put("tip",trash.getTrashTip());
            Date date=new Date();
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String s=sdf.format(date);
            values.put("dataTime",s);
            db.insert("history",null,values);
        }
    }


    @SuppressLint("Range")
    public List<History> loadHistory(){
        List<History> list=new ArrayList<>();
        Cursor cursor=db.query("history",null,null,null,null,null,null);
        if (cursor.moveToFirst()){
            do{
                History history=new History();
                history.setId(cursor.getInt(cursor.getColumnIndex("id")));
                history.setTrashName(cursor.getString(cursor.getColumnIndex("name")));
                history.setTrashType(cursor.getString(cursor.getColumnIndex("type")));
                history.setTrashTip(cursor.getString(cursor.getColumnIndex("tip")));
                history.setDataTime(cursor.getString(cursor.getColumnIndex("dataTime")));
                list.add(history);
            } while (cursor.moveToNext());
        }
        if (cursor!=null){
            cursor.close();
        }
        return list;
    }

    public void removeHistory(History history){
        int i=history.getId();
        String s= String.valueOf(i);
        db.delete("history","id=?",new String[]{s});
    }
}
